package cn.tworice.blog.service.impl;

import cn.tworice.blog.service.DyService;
import com.lmk.core.web.support.api.RequestResult;
import com.lmk.core.web.support.api.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *  解析抖音无水印
 * @author 二饭
 * @email 1786705138@qq.com
 */
@Service
@Slf4j
public class DyServiceImpl implements DyService {

    @Override
    public RequestResult getDouyinUrl(String url) {
        RequestResult result=new RequestResult();
        try {
            Map<String,Object> obj=getDyMp4Jsoup(url);
            result.appendData("httpsUrl",obj.get("urls"));
            result.appendData("httpUrl",obj.get("urlrest"));
            result.appendData("musicUrl",obj.get("uri"));
            result.setCode(new StatusCode(200,"解析成功！"));
        }catch (StringIndexOutOfBoundsException ex){
            result.setCode(new StatusCode(403,"解析失败，内容中应该有视频链接！"));
        }catch (Exception exception) {
            result.setCode(new StatusCode(403,"解析错误，请过一段时间再试！"));
            exception.printStackTrace();
        }
        return result;
    }

    public static Connection getConn(String url) {
        return Jsoup.connect(url).userAgent("Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1").ignoreContentType(true);
    }

    public static Map<String,Object> dyhtml(String url){

        Map<String,Object> restmap = new HashMap<String,Object>();

        try {
            Connection con = getConn(url);
            String recurl = getRedirectURL(con);
            String[] rest = recurl.split("video/");
            String[] mid = rest[1].split("/");
            String rceurl = "https://www.iesdouyin.com/web/api/v2/aweme/iteminfo/?item_ids="+mid[0];
            Connection reccon = getConn(rceurl);
            Connection.Response res = reccon.ignoreContentType(true).timeout(10000).execute();
            com.alibaba.fastjson.JSONObject json = com.alibaba.fastjson.JSONObject.parseObject(res.body());
            List<Map<String,Object>> maprest = (List<Map<String, Object>>) json.get("item_list");
            Map<String,Object> re = maprest.get(0);
            Map<String,Object> video = (Map<String, Object>) re.get("video");
            Map<String,Object> play_addr = (Map<String, Object>) video.get("play_addr");
            String urls = ((List<String>)play_addr.get("url_list")).get(0);
            urls = urls.replace("playwm", "play");
            restmap.put("urls", urls);
            Map<String,Object> music = (Map<String, Object>) re.get("music");
            Map<String,Object> play_url = (Map<String, Object>) music.get("play_url");
            String uri = play_url.get("uri")+"";
            restmap.put("uri", uri);
            return restmap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return restmap;
    }


    /**
     * 解析抖音
     * @param
     * @throws Exception
     * @throws Exception
     */
    public static Map<String,Object> getDyMp4Jsoup(String url1) throws Exception {
        //过滤链接，获取http连接地址
        String finalUrl = decodeHttpUrl(url1);
        String matchUrl = null;
        Map<String,Object> restmap = dyhtml(finalUrl);
        matchUrl = restmap.get("urls")+"";
        Connection connreturl = getConn(matchUrl);
        String urlrest = getRedirectURL(connreturl);
        restmap.put("urlrest", urlrest);
        return restmap;
    }

    private static String getRedirectURL(Connection conn) throws IOException {

        return conn.followRedirects(false).timeout(10000).execute().header("location");

    }



    public static String decodeHttpUrl(String url) {

        int start = url.indexOf("http");

        int end = url.lastIndexOf("/");

        String decodeurl = url.substring(start, end);

        return decodeurl;

    }
}
